package com.kitty.game.Qisha;


import com.kitty.common.utils.SpringUtils;
import com.kitty.common.utils.split;
import com.kitty.game.achieve.body.BossImgType;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.model.product.SuperBoss;
import com.kitty.game.activity.service.boos.service.BoosService;
import com.kitty.game.activity.service.other.SuperBossHandler;
import com.kitty.game.activity.service.time.FightActivityHandler;
import com.kitty.game.boss.config.BossSet;
import com.kitty.game.boss.model.*;
import com.kitty.game.boss.service.NewBossService;
import com.kitty.game.chat.service.ChatService;
import com.kitty.game.common.BoosTitleDeal;
import com.kitty.game.config.NPC;
import com.kitty.game.enter.TitleInfo;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.fight.ai.model.RoundSkillUnit;
import com.kitty.game.fight.bean.Fight;
import com.kitty.game.fight.bean.FightObject;
import com.kitty.game.fight.factory.model.NewBossFight;
import com.kitty.game.fight.service.FightService;
import com.kitty.game.fight.util.FightMessageUtil;
import com.kitty.game.i18n.I18nId;
import com.kitty.game.i18n.I18nIdDataPool;
import com.kitty.game.map.service.MapService;
import com.kitty.game.npc.NpcDataPool;
import com.kitty.game.npc.model.NpcButtonParam;
import com.kitty.game.npc.service.NewNpcService;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.team.model.Team;
import com.kitty.game.team.service.TeamService;
import com.kitty.game.utils.Const;
import com.kitty.listener.event.FightEndEvent;
import com.kitty.mina.annotation.RequestMapping;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.MessagePusher;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;

@Component
public class QishaController extends FightActivityHandler {

    @Autowired
    EquipService equipService;

    @Autowired
    ChatService chatService;

    private static final List<Byte> POLARS = Arrays.asList(Const.SCHOOL_METAL, Const.SCHOOL_WOOD, Const.SCHOOL_WATER, Const.SCHOOL_FIRE, Const.SCHOOL_EARTH);

    @Autowired
    protected TeamService teamService;
    @Autowired
    protected NewBossService bossService;
    @Autowired
    protected NewNpcService npcService;
    @Autowired
    private MapService mapService;
    @Autowired
    FightService fightService;
@Autowired
SuperBossHandler superBossHandler;
    private Map<String, SuperBoss> superBossMap = new HashMap<>();
    private static final String boy_name[] = {"七杀剑阵"};

    /**
     * 最少组队人数
     */
    private static final int MIN_TEAM_COUNT = 1;
    private static final String TEAM_COUNT_NOT_ENOUGH = "你还是凑齐三个人再来向我挑战吧!";
    private static final int ACCEPT_MIN_LEVEL = 40;
    private static final String TEAM_LEVEL_NOT_ENOUGH = "#Y{0}#n的等级还没有{1}级。";
    /**
     * 最大战胜次数
     */
    private static final short MAX_WIN_COUNT = 100;
    /**
     * 队员之间最大等级差
     */
    private static final int MAX_LEVEL_DIFF = 100;

    private static final Map<Byte, Integer> POLAR_SKILLS = new HashMap<>();

    private static final Map<Byte, Integer> POLAR_HELP_SKILLS = new HashMap<>();
    @PostConstruct
    private void init() {
        SuperBoss superBoss = new SuperBoss("七杀星君", 20063, 710);
        superBoss.getArtifactMap().put("番天印", 24);
        superBoss.getArtifactMap().put("混元金斗", 24);
        superBoss.getArtifactMap().put("番天印", 24);
        superBoss.getArtifactMap().put("定海珠", 6);
        superBoss.getArtifactMap().put("卸甲金葫", 24);
        superBoss.getArtifactMap().put("阴阳镜", 5);
        superBoss.setMainShowAfterRound((byte) 5);
        superBoss.setCallShowSmallAfterRound((byte) 6);
        //superBoss.setZPJSName("双龙护卫");
        superBoss.setSmallPolarRandom(true);
        superBoss.setSmallSkillRandom(true);
        superBoss.getPolarSmallSkills().put(Const.SCHOOL_METAL,Arrays.asList(12,13,15,31,32,33,35,25,23,22) );
        superBoss.getPolarSmallSkills().put(Const.SCHOOL_WOOD,Arrays.asList(62,63,65,81,82,83,85,75,75,75,75) );
        superBoss.getPolarSmallSkills().put(Const.SCHOOL_WATER,Arrays.asList(111,112,113,131,132,133,135) );
        superBoss.getPolarSmallSkills().put(Const.SCHOOL_FIRE,Arrays.asList(162,163,165,181,182,183,185,175,173,172) );
        superBoss.getPolarSmallSkills().put(Const.SCHOOL_EARTH,Arrays.asList(211,212,213,231,232,233,235,225,223,222) );
        superBossMap.put(superBoss.getName(), superBoss);

        /**各门派的5阶攻击技能*/
        POLAR_SKILLS.put(Const.SCHOOL_METAL, 15);
        POLAR_SKILLS.put(Const.SCHOOL_WOOD, 65);
        POLAR_SKILLS.put(Const.SCHOOL_WATER, 114);
        POLAR_SKILLS.put(Const.SCHOOL_FIRE, 165);
        POLAR_SKILLS.put(Const.SCHOOL_EARTH, 214);

        /**各门派的5阶障碍技能*/
        POLAR_HELP_SKILLS.put(Const.SCHOOL_METAL, 25);
        POLAR_HELP_SKILLS.put(Const.SCHOOL_WOOD, 75);
        POLAR_HELP_SKILLS.put(Const.SCHOOL_WATER, 125);
        POLAR_HELP_SKILLS.put(Const.SCHOOL_FIRE, 175);
        POLAR_HELP_SKILLS.put(Const.SCHOOL_EARTH, 225);
    }

    @RequestMapping
    public String XUEJING_ITEM(IoSession session, QishaRespMasterInfo qishaRespMasterInfo) {
        Role role = SessionUtils.getRoleBySession(session);

        NPC npc = new NPC();
        npc.setIcon(20063);
        npc.setId(SpringUtils.getBean(NewBossService.class).getTempNpcId());
		//原先是战神  注释了
		//npc.setType(NPC.TYPE_ZHAN_SHEN);
        npc.setType(NPC.TYPE_QISHA_TIAN);
        npc.setName("七杀星君");
        npc.setBossSetName("七杀星君");
        bossService.addTaskNpc(npc);

        String jiance = getNpcContentNotFight(role,npc);  //检测通过才下执行
        if(jiance!=null){
            MessagePusher.pushMessage(role, new RespMsg(jiance));
            return null;
        }
        split s= new split();
        List<String> list = s.StringSplit(qishaRespMasterInfo.getItems_pos());
        for(String xuejing:list){
            RoleEquip roleEquip = equipService.getRoleEquipByPos(role, Integer.parseInt(xuejing));
            equipService.delEquipNum(role,roleEquip,1);
        }
        String qisha = "qishazhandou";
        Consumer<NpcButtonParam> npcButtonHandler = NpcDataPool.npcButtonHandlers.get(qisha);
        if (npcButtonHandler != null) {
            npcButtonHandler.accept(new NpcButtonParam(role, npc, qisha, "1".equals("")));
            return null;
        }
        return null;
    }

    private int getRoleRemainCount(Role role) {
        return  SpringUtils.getActivityService().getRemainCount(role, ActivityType.QSXJ);
    }

    @Override
    protected String getNpcContent(Role role, NPC bossNpc) {
        return null;
    }

    @Override
    protected String getNpcContentNotFight(Role role, NPC bossNpc) {
        /**检测队伍人数*/
        int teamCount = teamService.getTeamCount(role);
        if (teamCount < MIN_TEAM_COUNT) {
            return TEAM_COUNT_NOT_ENOUGH;
        }

        /**检测等级*/
        Team team = teamService.getTeam(role.getRoleId());
        String names = teamService.checkMember(team, memberRole -> memberRole.getLevel() < ACCEPT_MIN_LEVEL);
        if (names != null) {
            return MessageFormat.format(TEAM_LEVEL_NOT_ENOUGH, names, ACCEPT_MIN_LEVEL);
        }

        /**
         * 检测挑战次数
         */
        names = teamService.checkMember(team, memberRole -> getRoleRemainCount(memberRole) <= 0);
        if (names != null) {
            return "#R" + names + "#n没有挑战次数";
        }
        if (getRoleRemainCount(role) <= 0) {
            return "#R" + role.getName() + "#n没有挑战次数";
        }

        /**
         * 队员之间最大等级差
         */
        names = teamService.checkMember(team, memberRole -> teamService.checkMember(team, mRole -> memberRole.getLevel() - mRole.getLevel() > MAX_LEVEL_DIFF) != null);
        if (names != null) {
            return I18nIdDataPool.getI18nContent(I18nId.PMT_1017, MAX_LEVEL_DIFF);
        }
        return null;
    }

    @Override
    protected void doStartFight(Role role, NPC bossNpc) {
        List<BossParam> bossParamList = newBossParamList(role, bossNpc);
        BossFightParam bossFightParam = new BossFightParam(bossParamList, getFightType(role));
        bossFightParam.setNpcId(bossNpc.getId());
        int maxRoleLevel = teamService.getMaxRoleLevelInTeam(role);
        bossFightParam.setNpcLevel((short) maxRoleLevel);
        Fight fight = bossService.startFightToBoss(role, bossFightParam);
        fight.setMaxRound(150);//战斗最大回合
    }


    @Override
    protected int getFightType(Role role) {
        return Const.fightType_qisha;
    }

    @Override
    protected NPC getBossNpc(int npcId) {
        return SpringUtils.getMapService().getNpc(npcId);
    }

    @Override
    protected void clearNpcAfterWin(Role role, NPC bossNpc) {

    }


    private SuperBoss getSuperBoss(String name) {
        return superBossMap.get(name);
    }

    private List<BossParam> newBossParamList(Role role, NPC bossNpc) {
        SuperBoss superBoss = getSuperBoss(bossNpc.getName());
        List<BossParam> bossParamList = new ArrayList<>();
        int count = 10;
        SuperBossParam superBossParam = newSuperBossParam(bossNpc);
        superBossParam.setMainShowAfterRound(superBoss.getMainShowAfterRound());
        superBossParam.setSmallEscapeAfterRound(superBoss.getSmallEscapeAfterRound());
        superBossParam.setCallShowSmallAfterRound(superBoss.getCallShowSmallAfterRound());
        if (superBoss.isSmallPolarRandom()) {
            byte polar = getRandomPolar();
            superBossParam.setPolar(polar);
        }
        if (superBoss.isSmallSkillRandom()) {
            ArrayList<Integer> skillIds = new ArrayList<>(superBoss.getPolarSmallSkills().get((byte)superBossParam.getPolar()));
            superBossParam.setSkillIds(skillIds);
        }
        bossParamList.add(superBossParam);
        /**加count-1个*/
        int smallCount = superBoss.getZPName() != null ? count - 1 : count;
      //  int smallJSCount = superBoss.getZPJSName() != null ? smallCount - 1 : smallCount;
        for (int i = 1; i < smallCount; i++) {
            int index = (int) (Math.random() * boy_name.length);
            BossSet bossSet = bossService.getBossSet(boy_name[index]);
            BossParam bossParam = new BossParam(bossSet, bossSet.getName());
            if (superBoss.isSmallPolarRandom()) {
                byte polar = SpringUtils.getBean(BoosService.class).getRandomPolar();
                bossParam.setPolar(polar);
            }
            if (superBoss.isSmallSkillRandom()) {
                ArrayList<Integer> skillIds = new ArrayList<>(superBoss.getPolarSmallSkills().get((byte) bossParam.getPolar()));
                bossParam.setSkillIds(skillIds);
            }
            bossParamList.add(bossParam);
        }
        if (superBoss.getZPName() != null) {
            BossSet bossSet = bossService.getBossSet(superBoss.getZPName());
            bossParamList.add(new SuperBossZPParam(bossSet, bossSet.getName()));
        }
//        if (superBoss.getZPJSName() != null) {
//            BossSet bossSet = bossService.getBossSet(superBoss.getZPJSName());
//            bossParamList.add(new SuperBossZPJSParam(bossSet, bossSet.getName()));
//        }
        return bossParamList;
    }

    /**获得随机相性*/
    private byte getRandomPolar() {
        int index = ThreadLocalRandom.current().nextInt(POLARS.size());
        return POLARS.get(index);
    }


    private SuperBossParam newSuperBossParam(NPC bossNpc) {
        SuperBoss superBoss = getSuperBoss(bossNpc.getName());
        BossSet bossSet = bossService.getBossSet(bossNpc.getName());
        SuperBossParam bossParam = new SuperBossParam(bossSet, bossNpc.getName());
        /**随机相性*/
        byte polar = getRandomPolar();
        bossParam.setPolar(polar);
        /**获得对应的技能*/
        ArrayList<Integer> skillIds = getSkillIdsMatchPolar(polar);
        bossParam.setSkillIds(skillIds);
        bossParam.setRoundSkills(getRoundSkills(polar, superBoss));
        /**对应的法宝*/
        bossParam.setArtifactMap(superBoss.getArtifactMap());
        return bossParam;
    }

    public List<RoundSkillUnit> getRoundSkills(byte polar, SuperBoss superBoss) {
        List<RoundSkillUnit> list = new ArrayList<>();
        //妖皇天怒  超级技能
        list.add(new RoundSkillUnit(5, 5, superBoss.getSkillId()));
        Integer skillId = POLAR_HELP_SKILLS.get(polar);
        list.add(new RoundSkillUnit(6, 5, skillId));
        return list;
    }

    /**获得匹配相性的技能ID列表*/
    private ArrayList<Integer> getSkillIdsMatchPolar(byte polar) {
        ArrayList<Integer> skilIds = new ArrayList<>();
        /**相性的技能*/
        //Integer skillId = POLAR_SKILLS.get(polar);
        //skilIds.add(skillId);

        /**力破千钧*/
        skilIds.add(501);
        /**普通攻击*/
        skilIds.add(2);

        return skilIds;
    }


    @Override
    protected void giveReward(Role role, FightEndEvent fightEndEvent, NPC bossNpc) {
        // 这里改成公共获取配置 经验，道行，武学 奖励。 不再单独写
        fightService.sendBossBasicsReward(role,fightEndEvent);
        //SpringUtils.getActivityService().addFinishCount(role, ActivityType.QSXJ, 1);
        fightService.sendBossExtReward(role,fightEndEvent);
    }

    @Override
    protected void clearNpcTimeOut(NPC npc) {
        timeOut(npc);
    }

    private void timeOut(NPC npc) {
        /**已经消失*/
        if (mapService.getNpc(npc.getId()) == null) {return ;}

        clearSuperBoss(npc);
    }

    private void clearSuperBoss(NPC npc) {
        if (npc == null) {
            return;
        }

        SuperBoss superBoss = getSuperBoss(npc.getName());
        superBoss.setMapId(0);
        bossService.delTaskNpc(npc);
        bossService.broadcastNpcHide(null, npc);
        removeUsedPosition(npc.getMapId(), npc.getX(), npc.getY());
    }

    @Override
    public void doFightFail(Role role, FightEndEvent fightEndEvent) {
        super.doFightFail(role, fightEndEvent);
        NPC npc = mapService.getNpc(fightEndEvent.getNpcId());
        if (npc != null){
            SuperBoss superBoss = getSuperBoss(npc.getName());
            superBoss.setFightCount(superBoss.getFightCount() - 1);
        }
        teamService.memberHandleThreadLocal(role, memberRole -> SpringUtils.getRoleService().punishFightDead(memberRole));
    }


    @Override
    public void doFightWin(Role role, FightEndEvent fightEndEvent) {
        NPC npc = mapService.getNpc(fightEndEvent.getNpcId());
        if (npc != null){
            SuperBoss superBoss = getSuperBoss(npc.getName());
            superBoss.setWinCount(superBoss.getWinCount() + 1);
            /**胜利次数达到最大值*/
            if (superBoss.getWinCount() >= MAX_WIN_COUNT) {
                if (npc != null) {
                    clearSuperBoss(npc);
                }
            }
        }
        super.doFightWin(role, fightEndEvent);
        teamService.memberHandleThreadLocal(role, memberRole -> SpringUtils.getActivityService().addFinishCount(memberRole, ActivityType.QSXJ, 1));
    }

    @Override
    public void doFightRunAway(Role role, FightEndEvent fightEndEvent) {
        super.doFightRunAway(role, fightEndEvent);
        NPC npc = mapService.getNpc(fightEndEvent.getNpcId());
        if (npc != null){
            SuperBoss superBoss = getSuperBoss(npc.getName());
            superBoss.setFightCount(superBoss.getFightCount() - 1);
        }

        teamService.memberHandleThreadLocal(role, memberRole -> SpringUtils.getRoleService().punishFightDead(memberRole));
    }

    @Override
    public void doFightMaxRound(Role role, FightEndEvent fightEndEvent) {
        super.doFightMaxRound(role, fightEndEvent);
        NPC npc = mapService.getNpc(fightEndEvent.getNpcId());
        SuperBoss superBoss = getSuperBoss(npc.getName());
        superBoss.setFightCount(superBoss.getFightCount() - 1);
    }

    @Override
    public boolean isSetInFight() {
        /**不需要设置进入战斗状态，可以同时进入战斗*/
        return false;
    }
    @Override
    public void doFightWinForTeam(Team team, FightEndEvent fightEndEvent, NPC bossNpc) {
//        if(SuperBossHandler.SUPER_BOSS_LIST.contains(bossNpc.getName())){
//            teamService.memberHandleThreadLocal(team, role -> {
//                giveReward(role, fightEndEvent, bossNpc);
//            });
//        }
        final Boolean[] flag = {false};
        List<Map<String, String>> list = SpringUtils.getBean(BoosTitleDeal.class).getBossTitleInfo("qisha");
        teamService.memberHandleThreadLocal(team, role -> {
            /**发称号*/
            if (list.size() <= 0) {
                SpringUtils.getRoleService().addTitle(role, new TitleInfo("神武中洲·七杀试炼", "神武中洲·七杀试炼"));
                SpringUtils.getBean(BoosTitleDeal.class).addBoosTitle(role.getName(), "qisha", "神武中洲·七杀试炼");
                SpringUtils.getBean(RoleService.class).addAchieveScore(role,"602037");
                flag[0] = true;
            }
            giveReward(role, fightEndEvent, bossNpc);
            addRoleBossImg(role, BossImgType.QISHAXINGJUN);
        });
        // 更新数据库首次称号奖励
        if (flag[0]) {
            sendShouShaReward(team,bossNpc,"神武中洲·七杀试炼");

            SpringUtils.getBean(BoosTitleDeal.class).updateBoosTitle();
        }

    }
    public void fightQiSha(Fight fight){
        NewBossFight bossFight = (NewBossFight)fight;
        /**
         * 第六回合召唤两个 护卫双龙，
         * 第七回合开始 每回合召唤一个 镇邪四象
         * 第十回合召唤 一气化三清？
         */
        int is_side_over = fight.getData().getInt("is_side_over", 0);
        if(fight.getRound() == is_side_over+2) {
            List<FightObject> list = new ArrayList<>(fight.getListB());
            for (FightObject fightObject : list) {
                if(!"七杀星君".equals(fightObject.getName())){
                    FightMessageUtil.sendFightPackage(fight, SpringUtils.getFightMessageService().disappear(fightObject.getId()));
                    fight.removeFightObject(fightObject);
                }
            }
            HashMap<Integer,String> conentMap = new HashMap<>();
            //生成两个 “双龙护卫"
            HashMap<Integer,String> map = new HashMap<Integer,String>();
            map.put(1,"双龙护卫");
            conentMap.put(1,"双龙护卫前来觐见");
            map.put(2,"双龙护卫");
            conentMap.put(2,"双龙护卫前来觐见");
            superBossHandler.addBossMapInFight(fight,map,conentMap);
        }
        if(fight.getRound() > is_side_over+2 && fight.getRound()%3==0) {
            List<FightObject> list = new ArrayList<>(fight.getListB());
            if(list.size()<10){
                //生成一个 “四象镇邪"
                HashMap<Integer,String> conentMap = new HashMap<>();
                int fightNotUsePos = superBossHandler.getFightNotUsePos(fight);
                conentMap.put(fightNotUsePos,"诛邪！");
                HashMap<Integer,String> map = new HashMap<Integer,String>();
                map.put(fightNotUsePos,"四象镇邪");
                superBossHandler.addBossMapInFight(fight,map,conentMap);
            }
        }
        //第十回合 一气化三清
        if(fight.getRound()== is_side_over+6) {
            HashMap<Integer,String> conentMap = new HashMap<>();
            conentMap.put(5,"一气化三清！");
            conentMap.put(6,"一气化三清！");
            conentMap.put(7,"一气化三清！");
            //生成三个七杀分身"
            HashMap<Integer,String> map = new HashMap<Integer,String>();
            map.put(5,"七杀星君分身");
            map.put(6,"七杀星君分身");
            map.put(7,"七杀星君分身");
            superBossHandler.addBossMapInFight(fight,map,conentMap);
        }
    }
}
